package com.easy.carpanel.uart;

import android.util.Log;


import com.car.carcontrol.utils.TransformUtils;
import com.example.x6.serial.SerialPort;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 七寸屏和设备串口通信
 * Created by yuanyi on 2020/5/30.
 */
public class uartJnit {
    static {
        System.loadLibrary("uart_phx");
    }
    public static  int fd;
    public static native int open(String name, int baud);

    public static native int close(int fd);

    public static native int read(int fd, byte[] buf, int len);

    public static native int write(int fd, byte[] buf, int len);

    private OnDataReceiveListener onDataReceiveListener = null;
    private String TAG = uartJni.class.getSimpleName();
    private SerialPort mSerialPort;
    private OutputStream mOutputStream;
    private InputStream mInputStream;
    private ReadThread mReadThread;
    // private String path = "/dev/ttyMT1";
    private String path = "/dev/ttyS3";
    private static  int baudrate = 115200;
    private static uartJnit portUtil;
 //   private OnDataReceiveListener onDataReceiveListener = null;
    private boolean isStop = false;

    public interface OnDataReceiveListener {
        public void onDataReceive(byte[] buffer, int size);
    }

    public void setOnDataReceiveListener(
            OnDataReceiveListener dataReceiveListener) {
        onDataReceiveListener = dataReceiveListener;
    }

    public  static void discon()
    {
       uartJnit.portUtil=null;
    }
    public  static void sclose()
    {
        fd =  uartJnit.getInstance().fd;
        close(fd);
    }

    public static uartJnit getInstance() {
        if (null == portUtil) {
            portUtil = new uartJnit();
            portUtil.sonCreate();
        }
        return portUtil;
    }
    public static  void sonCreate() {
        String device = "/dev/ttyS3";
        fd = uartJni.open(device, baudrate);
      //  Log.d(TAG, "open the device of " + device + ", fd is: " + fd);
    }
//    /**
//     * 初始化串口信息
//     */
//    public void onCreate() {
//        try {
////            String device = "/dev/ttyS3";
////            fd = uartJni.open(device, 11520);
//
//            mSerialPort = new SerialPort(path, baudrate);
//            mOutputStream = mSerialPort.getOutputStream();
//            mInputStream = mSerialPort.getInputStream();
//
//            mReadThread = new ReadThread();
//            isStop = false;
//            mReadThread.start();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        // initBle();
//    }


    private static final int MIN_CLICK_DELAY_TIME = 50;
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }


    private static final int MAX_LONG_DELAY_TIME = 3000;
    private static long lastSendTime;

    public static boolean isClickGone() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastSendTime) >= MAX_LONG_DELAY_TIME) {
            flag = true;
        }
        // lastSendTime = curClickTime;
        return flag;
    }
    /**
     * 发送指令到串口
     *
     * @param cmd
     * @return
     */
    public boolean sendCmds(String cmd) {
//        byte[] write_buf1 = new byte[] {0x5a, (byte) 0xa5, 0x08, (byte)0x83, 0x01, 0x01, 0x01, 0x00, 0x01, 0x00, (byte) 0xff};
//        byte[] write_buf2 = new byte[] {0x5a, (byte) 0xa5, 0x08, (byte)0x83, 0x01, 0x02, 0x01, 0x00, 0x01, 0x00, (byte) 0xff};
//        int write_count = uartJni.write(fd, write_buf1, write_buf1.length);

        boolean result = true;
       // byte[] mBuffer = (cmd + "\r\n").getBytes();
     //  byte[] mBuffer = cmd.getBytes();
        byte[] mBuffer =  TransformUtils.hexStringToBytes(cmd);
       // byte[] mBuffer =  new byte[] {0x5a, (byte) 0xa5, 0x08, (byte)0x83, 0x01, 0x01, 0x01, 0x00, 0x01, 0x00, (byte) 0xff};
//注意：我得项目中需要在每次发送后面加\r\n，大家根据项目项目做修改，也可以去掉，直接发送mBuffer
        try {
            int write_count = uartJni.write(fd, mBuffer, mBuffer.length);
//            if (mOutputStream != null) {
//                mOutputStream.write(mBuffer);
//            } else {
//                result = false;
//            }
                    if (write_count < 0) {
                        result = false;
          //  Log.e(TAG, "oncesendbuf: error" );
        }

        } catch (Exception e) {
            e.printStackTrace();
            result = false;
        }
        return result;
    }

//    sendThread = new Thread() {
//        @Override
//        public void run() {
//            while (true) {
//                try {
//                    i++;
//                    mOutputStream.write((String.valueOf(i)).getBytes());
//                    Log.i("test", "发送成功:1" + i);
//                    Thread.sleep(1);
//                } catch (Exception e) {
//                    Log.i("test", "发送失败");
//                    e.printStackTrace();
//                }
//            }
//        }
//    };
//                sendThread.start();


    public boolean sendBuffer(byte[] mBuffer) {
        boolean result = true;
        String tail = "\r\n";
        byte[] tailBuffer = tail.getBytes();
        byte[] mBufferTemp = new byte[mBuffer.length + tailBuffer.length];
        System.arraycopy(mBuffer, 0, mBufferTemp, 0, mBuffer.length);
        System.arraycopy(tailBuffer, 0, mBufferTemp, mBuffer.length, tailBuffer.length);
//注意：我得项目中需要在每次发送后面加\r\n，大家根据项目项目做修改，也可以去掉，直接发送mBuffer
        try {
            if (mOutputStream != null) {
                mOutputStream.write(mBufferTemp);
            } else {
                result = false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            result = false;
        }
        return result;
    }

    private class ReadThread extends Thread {

        @Override
        public void run() {
            super.run();
            while (!isStop && !isInterrupted()) {
                int size;
                try {
                    if (mInputStream == null)
                        return;
                    byte[] buffer = new byte[512];
                    size = mInputStream.read(buffer);
                    if (size > 0) {
//                        if(MyLog.isDyeLevel()){
//                            MyLog.log(TAG, MyLog.DYE_LOG_LEVEL, "length is:"+size+",data is:"+new String(buffer, 0, size));
//                        }
                        if (null != onDataReceiveListener) {
                            onDataReceiveListener.onDataReceive(buffer, size);
                        }
                    }
                    Thread.sleep(10);
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }
            }
        }
    }

    /**
     * 关闭串口
     */
    public    void closeSerialPort() {
        //  sendShellCommond1();
        isStop = true;
        if (mReadThread != null) {
            mReadThread.interrupt();
        }
        if (mSerialPort != null) {
            mSerialPort.close();
        }
    }

}